package ltd.bugs.cute.urm.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.auth0.jwt.JWT;

import ltd.bugs.cute.api.http.RestResponse;
import ltd.bugs.cute.api.http.statuscode.CommonStatusCode;
import ltd.bugs.cute.common.session.SecuritySession;
import ltd.bugs.cute.jwt.utils.JWTUtils;
import ltd.bugs.cute.urm.annotation.UrmAPI;
import ltd.bugs.cute.urm.controller.request.LoginRequest;
import ltd.bugs.cute.urm.jwt.PermJwtParams;
import ltd.bugs.cute.urm.manager.MenuManager;
import ltd.bugs.cute.urm.manager.UserManager;
import ltd.bugs.cute.urm.model.User;
import ltd.bugs.cute.web.exception.BizException;

@Controller
public class IndexController {

  @Autowired
  private UserManager userManager;
  @Autowired
  private MenuManager menuManager;

  @RequestMapping("/admin")
  @UrmAPI(checkMenuPerm = false, needLogin = false)
  public String index(HttpServletRequest request, Model model) {
    // 登录过，直接跳转到主页
    if (SecuritySession.get() != null) {
      return main(model);
    }

    return "login";
  }

  @RequestMapping("/admin/login")
  @ResponseBody
  @UrmAPI(checkMenuPerm = false, needLogin = false)
  public RestResponse login(@Validated LoginRequest loginRequest, HttpServletResponse response) {
    User user = userManager.authentication(loginRequest.getUsername(), loginRequest.getPassword());
    if (user == null) {
      throw new BizException(CommonStatusCode.UNAUTHORIZED, "用户名或密码错误");
    }
    // 根据user对象生成token，并设置到response cookie中。为确保安全，cookie为http only
    String token = JWT.create().withIssuer(JWTUtils.issuer)
        .withClaim(PermJwtParams.UID, user.getId()).sign(JWTUtils.algorithm);
    Cookie cookie = new Cookie(PermJwtParams.COOKIE_NAME, token);
    // 开发环境下有问题，暂时注释
    // cookie.setHttpOnly(true);
    response.addCookie(cookie);

    return RestResponse.SUCCESS;
  }

  @RequestMapping("/admin/main")
  @UrmAPI(checkMenuPerm = false, needLogin = true)
  public String main(Model model) {
    // 获取左侧菜单
    User user = SecuritySession.get(User.class);
    model.addAttribute("menuList", menuManager.getMenuList(user));
    model.addAttribute("user", user);
    // 获取菜单
    return "main";
  }

  @RequestMapping(value = "/admin/logout")
  @UrmAPI(checkMenuPerm = false, needLogin = false)
  public String logout(HttpServletResponse response) {
    Cookie cookie = new Cookie(PermJwtParams.COOKIE_NAME, "");
    response.addCookie(cookie);

    return "redirect:/admin";
  }
}
